package com.itheima.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class RecommendMovementTask {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MongoTemplate mongoTemplate;

    //TODO 项目上线后可以改成每半个小时同步一次
    @Scheduled(cron = "0/30 * * * * ?")
    public void syncRecommendMovement(){
        System.out.println("---动态推荐任务开始执行");
        //目标:将reids中推荐给某个用户的动态的pid字符串保存到mongo的recommendMovement表中
        //1.先获取redis中所有推荐动态的key  MOVEMENTS_RECOMMEND_99  MOVEMENTS_RECOMMEND_9 ...
        Set<String> keySet = stringRedisTemplate.keys("MOVEMENTS_RECOMMEND_*");

        //2.遍历key的集合,获取推荐给每个用户的pid字符串 (23,25,19,21)
        if (CollUtil.isNotEmpty(keySet)) {
            keySet.forEach(key->{
                //3.保存之前先把mongo中推荐给当前用户的数据先删除一下
                Long userId = Long.parseLong(key.replace("MOVEMENTS_RECOMMEND_", ""));
                mongoTemplate.remove(new Query(Criteria.where("userId").is(userId)), RecommendMovement.class);

                //key  MOVEMENTS_RECOMMEND_99
                //4.获取推荐给每个用户的pid字符串
                String pidStrs = stringRedisTemplate.opsForValue().get(key);

                //5.分割字符串获取每个动态的pid
                String[] pidArr = pidStrs.split(",");

                //6.遍历数组,获取每个动态pid,
                for (String pidStr : pidArr) {
                    long pid = Long.parseLong(pidStr);

                    //7.查询动态表获取每个动态的id
                    Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(pid)), Movement.class);

                    //8.将上面的信息封装成RecommendMovement对象
                    RecommendMovement recommendMovement = new RecommendMovement();
                    recommendMovement.setCreated(System.currentTimeMillis());
                    recommendMovement.setUserId(userId);
                    recommendMovement.setPid(pid);
                    recommendMovement.setPublishId(movement.getId());
                    recommendMovement.setScore(RandomUtil.randomDouble(80,99));

                    //9.将数据保存到推荐动态表中
                    mongoTemplate.save(recommendMovement);
                }
            });
        }
        System.out.println("---动态推荐任务执行结束");
    }

}
